package com.yimi.yinhepda.views.offline.unload;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.pda.ym.base.BaseActivity;
import com.yimi.yinhepda.R;
import com.yimi.yinhepda.adapter.unload_offline.UnloadOffLineAddAdapter;
import com.yimi.yinhepda.db.dao.ScanDetailVoDao;
import com.yimi.yinhepda.db.dao.UnloadScanTableDao;
import com.yimi.yinhepda.db.dao.UnloadTaskTableDao;
import com.yimi.yinhepda.db.table.ScanDetailVo;
import com.pda.ym.db.table.UnloadScanTable;
import com.yimi.yinhepda.db.table.UnloadTaskTable;
import com.yimi.yinhepda.entity.bean.AddEntity;
import com.yimi.yinhepda.utils.Common;
import com.pda.ym.utils.Constants;
import com.pda.ym.utils.DateHelper;
import com.pda.uce.commom.util.LogUtil;
import com.pda.ym.utils.SoundVibratorManager;
import com.pda.ym.utils.StringUtils;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 离线卸车手动添加界面
 * Created by 000432 on 2017/9/12
 *
 * @author lj
 */

public class OffLineUnloadAddActivity extends BaseActivity implements View.OnClickListener {

    private TextView mNum;
    private EditText mAddInput;
    private Button mBtnAdd;
    private ListView mAddListView;
    private TextView mShowAddCount;
    private Button mAddBack;
    private Button mAddOk;
    private List<AddEntity> mChildWayBills = new ArrayList<>();
    /**
     * 卸车标志
     */
    private int operTypeCode = 4;
    private String userCode;
    private UnloadScanTableDao mUnloadScanTableDao;
    private ScanDetailVoDao scanDetailVoDao;
    private UnloadTaskTableDao taskTableDao;
    /**
     * 本地任务编号
     */
    private String offlineTaskNo;
    private List<ScanDetailVo> scanList;
    /**
     * 配载单对象
     */
    private UnloadTaskTable taskTable;
    private UnloadOffLineAddAdapter unloadOffLineAddAdapter;
    private String platformNo;
    private String joinUserName;
    private String joinWrokNum;

    public OffLineUnloadAddActivity() {
        super(true);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_unload_offline);

        initView();
        initEvent();
        initData();
    }

    @Override
    public String getPageName() {
        return "手动添加单号";
    }

    public void initView() {
        TextView mTitle =  findViewById(R.id.title);
        mNum =  findViewById(R.id.num);
        mShowAddCount =  findViewById(R.id.show_add_count);
        mAddInput =  findViewById(R.id.offline_add_input);
        mBtnAdd =  findViewById(R.id.add_offline_btn);
        mAddListView =  findViewById(R.id.offline_add_listview);
        mAddBack =  findViewById(R.id.add_childwaybill_back);
        mAddOk =  findViewById(R.id.add_childwaybill_ok);
        mTitle.setText("手动添加单号");
    }

    public void initEvent() {
        mBtnAdd.setOnClickListener(this);
        mAddBack.setOnClickListener(this);
        mAddOk.setOnClickListener(this);
    }

    public void initData() {
        platformNo = getIntent().getStringExtra("platformNo");
        joinUserName = getIntent().getStringExtra("joinUserName");
        joinWrokNum = getIntent().getStringExtra("joinWrokNum");

        mUnloadScanTableDao = new UnloadScanTableDao();
        scanDetailVoDao = new ScanDetailVoDao();
        taskTableDao = new UnloadTaskTableDao();

        userCode = sharedPreferUtil.getValue(Common.USER_CODE);

        offlineTaskNo = getIntent().getStringExtra("offlineTaskNo");
        if (offlineTaskNo == null) {
            offlineTaskNo = "";
        }
        scanList = scanDetailVoDao.getDataByStowageAndType(offlineTaskNo, operTypeCode, userCode);
        if (scanList == null) {
            scanList = new ArrayList<>();
        }
        List<UnloadTaskTable> stowage = taskTableDao.findStowage(offlineTaskNo, userCode);
        if (stowage != null && !stowage.isEmpty()) {
            taskTable = stowage.get(0);
        }

        unloadOffLineAddAdapter = new UnloadOffLineAddAdapter(this, mChildWayBills);
        mAddListView.setAdapter(unloadOffLineAddAdapter);
        //设置未上传数
        mNum.setText((int) mUnloadScanTableDao.queryCount("isUpload", 0, operTypeCode) + "");
    }

    @Override
    protected void handleBarCode(String result) {
        if (result == null) {
            SoundVibratorManager.playSound(2);
            showToast("运单号扫描失败");
        } else {
            mAddInput.setText(result);
            doScan(result);
        }
    }

    /**
     * 处理扫描
     */
    protected void doScan(String result) {
        if (!StringUtils.isWaybillNo(result) && !StringUtils.isPackgeNo(result)) {
            SoundVibratorManager.playSound(2);
            showToast("单号或包号不规范!");
            return;
        }
        //判断子单是否已扫
        List<UnloadScanTable> childWaybillNo = mUnloadScanTableDao.getChildWaybillNo(offlineTaskNo, operTypeCode, userCode, result);
        if (childWaybillNo != null && !childWaybillNo.isEmpty()) {
            SoundVibratorManager.playSound(2);
            showToast("运单已扫描!");
            return;
        }
        //判断运单是否存在
        boolean isExitWayBillNo = false;
        String wayBillNo = result.substring(0, 12);
        if (scanList != null && !scanList.isEmpty()) {
            for (ScanDetailVo scanDetailVo : scanList) {
                if (scanDetailVo.getWaybillNo().equals(wayBillNo)) {
                    isExitWayBillNo = true;
                    //更新数据库
                    scanDetailVo.setQuantity(scanDetailVo.getQuantity() + 1);
                    scanDetailVo.setScanTime(DateHelper.getDateFormateOffline());
                    try {
                        scanDetailVoDao.update(scanDetailVo);
                        //保存运单
                        UnloadScanTable unloadScanTable = saveWaybill(result, 1);
                        mUnloadScanTableDao.insert(unloadScanTable);
                        //更新配载单件数
                        taskTable.setPiecesNum(taskTable.getPiecesNum() + 1);
                        taskTableDao.update(taskTable);

                        //listView添加数据
                        mChildWayBills.add(new AddEntity(wayBillNo, result));
                    } catch (SQLException e) {
                        LogUtil.e(e.toString());
                    }
                }
            }
            unloadOffLineAddAdapter.notifyDataSetChanged();
        }
        if (!isExitWayBillNo) {
            ScanDetailVo scanDetail = new ScanDetailVo();
            scanDetail.setWaybillNo(wayBillNo);
            scanDetail.setInputType(1);
            scanDetail.setQuantity(1);
            scanDetail.setScanTime(DateHelper.getDateFormateOffline());
            scanDetail.setOfflineTaskNo(offlineTaskNo);
            scanDetail.setOperTypeCode(operTypeCode);
            scanDetail.setOperEmpCode(sharedPreferUtil.getValue(Common.USER_CODE));
            //更新列表
            scanList.add(scanDetail);
            //保存运单
            UnloadScanTable unloadScanTable = saveWaybill(result, 1);
            try {
                //不在列表中，更新件数
                taskTable.setPiecesNum(taskTable.getPiecesNum() + 1);
                taskTable.setPriceNum(taskTable.getPriceNum() + 1);
                taskTableDao.update(taskTable);
                scanDetailVoDao.insert(scanDetail);
                mUnloadScanTableDao.insert(unloadScanTable);
            } catch (SQLException e) {
                LogUtil.e(e.toString());
            }
            //listView添加数据
            mChildWayBills.add(new AddEntity(wayBillNo, result));
            unloadOffLineAddAdapter.notifyDataSetChanged();
        }

        //设置总票，总件数
        if (mChildWayBills != null && !mChildWayBills.isEmpty()) {
            Set<String> set = new HashSet<>();
            for (AddEntity item : mChildWayBills) {
                set.add(item.getWaybillNum());
            }
            mShowAddCount.setText(set.size() + "/" + mChildWayBills.size());
        }

        //设置未上传数
        mNum.setText((int) mUnloadScanTableDao.queryCount("isUpload", 0, operTypeCode) + "");
        SoundVibratorManager.playSound(1);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.add_offline_btn:
                String childWayBill = mAddInput.getText().toString();
                if (TextUtils.isEmpty(childWayBill)) {
                    SoundVibratorManager.playSound(2);
                    showToast("请先输入需要手动添加的单号！");
                    return;
                }
                doScan(childWayBill);
                break;
            case R.id.add_childwaybill_back:
                backMethod();
                break;
            case R.id.add_childwaybill_ok:
                backMethod();
                break;
            default:
                break;
        }
    }

    private void backMethod() {
        Bundle bundle = new Bundle();
        bundle.putString("offlineTaskNo", offlineTaskNo);
        setResult(OffLineUnloadActivity.ADD_DELETE_RESULTOK, this.getIntent().putExtras(bundle));
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return false;
    }

    /**
     * 保存运单
     */
    private UnloadScanTable saveWaybill(String result, int type) {
        UnloadScanTable unloadScan = new UnloadScanTable();
        unloadScan.setScanTime(Constants.getCurrentTimeFormat1()); //时间
        unloadScan.setOperTime(DateHelper.getDateTimeFormate(null));
        unloadScan.setChildWaybillNo(result); // 子单
        unloadScan.setWaybillNo(result.substring(0, 12)); // 主单
        unloadScan.setInputType(type); // 扫描类型
        unloadScan.setOperTypeCode(4); // 操作类型 卸车
        unloadScan.setOfflineTaskNo(offlineTaskNo); // 配载单号
        unloadScan.setOperEmpCode(sharedPreferUtil.getValue(Common.USER_CODE));
        //设置月台号
        unloadScan.setPlatformNo(platformNo);
        //装卸组参与人
        unloadScan.setOperPersonNames(joinUserName);
        unloadScan.setOperPersonCodes(joinWrokNum);
        return unloadScan;
    }
}
